﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.LeaveCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.LeaveHandler
{
    public class CreateLeaveHandler : IRequestHandler<CreateLeaveCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Leave> leaveRep;
        private readonly IBaseRepository<Record> reRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<User> userRep;

        public CreateLeaveHandler(IBaseRepository<Leave> leaveRep,IBaseRepository<Record> reRep,IMapper mapper,IBaseRepository<User> userRep)
        {
            this.leaveRep = leaveRep;
            this.reRep = reRep;
            this.mapper = mapper;
            this.userRep = userRep;
        }
        public async Task<APIResult<int>> Handle(CreateLeaveCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            //请假申请表的添加
            var model = mapper.Map<Leave>(request);          
            model.ApprovalStatus = (int)ApprovalStatus.待审核;
            model.ApprovalStatusName=ApprovalStatus.待审核.ToString();
            model.CreateTime = DateTime.Now;
            model.UpdateUser = "";
            model.IsDeleted = false;

            //判断当前登录人是否是领导
            var u2 = userRep.GetAll().Where(x => x.UserId == request.LeaveId&&x.PowerId==(int)PowerId.部门领导人);
            if (u2.Count()>0) 
            {
                //是领导人
                var ids = userRep.GetAll().Where(x=>x.PowerId==(int)PowerId.总负责人).Select(x=>x.UserId);
                model.LeaderIds=string.Join(",", ids);
                var name= userRep.GetAll().Where(x => x.PowerId == (int)PowerId.总负责人).Select(x => x.Name);
                model.LeaderName=string.Join(",", name);
            }
            else
            {
                //不是领导人
                //通过部门id和领导人查到所有领导人的id

                var u = userRep.GetAll().Where(x=>x.DepartmentId==request.DepartmentId&&x.PowerId==(int)PowerId.部门领导人);
                var Lids=u.Select(x=>x.UserId);
                model.LeaderIds =string.Join(",", Lids);
                var Lname=u.Select(x=>x.Name);
                model.LeaderName =string.Join(",", Lname);
            }

            result.Code=APIEnum.Success;
            result.Msg = "添加成功";
            result.Data = 1;
            await leaveRep.AddAsync(model);
            //记录表的添加
            var record=new Record();
            record.LeaveId=model.LeaveId;
            record.OperatorId = model.LeaveId;
            record.OperatorName=model.LeaveName; 
            record.AppResult=(int)ApprovalStatus.待审核;
            record.Reason=ApprovalStatus.待审核.ToString();
            record.CreateTime = DateTime.Now;
            await reRep.AddAsync(record);
            return await Task.FromResult(result);
        }
    }
}
